package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;
import com.lagou.rpc.consumer.client.TestRoundRobin;
import com.lagou.rpc.consumer.zookeeper.ZookeeperClientOperation;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ReflectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
public class RpcClientProxy {

    private static final Logger LOGGER = LoggerFactory.getLogger(RpcClientProxy.class);

    private static final String zookeeperAddress = "127.0.0.1:2181";

    private static final String ROOT_NODE = "/lg-provider";

    public static Object createProxy(Class<?> serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);

                        //2.创建RpcClient对象
                        //此处来模拟负载均衡轮询模拟调用多个服务端中的一个
                        TestRoundRobin testRoundRobin=new TestRoundRobin();
                        String serverIpAndPort = testRoundRobin.RoundRobin();
                        String[] array = serverIpAndPort.split(":");
                        RpcClient rpcClient = new RpcClient(array[0], Integer.parseInt(array[1]));

//                        ZookeeperClientOperation zookeeperClientOperation = new ZookeeperClientOperation();
//                        RpcClient rpcClient = zookeeperClientOperation.getRpcClient();
//                        if (rpcClient == null){
//                            throw new RuntimeException("未找到 lg-rpc-provider 服务提供者");
//                        }
                        LOGGER.info("调用的服务提供者的ip+端口号为:{}", serverIpAndPort);

                        try {
                            //3.发送消息，记录调用服务端响应时间
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            // 响应时间
                            long responseTime = System.currentTimeMillis();
                            //4.更新服务响应时间
                            ZkClient zkClient = new ZkClient(zookeeperAddress);
                            String nodeName = ROOT_NODE + "/" + rpcClient.getAddress();
                            zkClient.writeData(nodeName, responseTime, -1);

                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            int fromRpcPort = rpcResponse.getFromRpcPort();
                            Field fromPortField = ReflectionUtils.findField(method.getReturnType(), "fromPort");
                            if (fromPortField != null) {
                                fromPortField.setAccessible(true);
                            }
                            Object beanResult = JSON.parseObject(result.toString(), method.getReturnType());
                            if (fromPortField != null) {
                                ReflectionUtils.setField(fromPortField, beanResult, fromRpcPort);
                            }
                            return beanResult;
                        } catch (Exception e) {
                            throw e;
                        } finally {
                            rpcClient.close();
                        }

                    }
                });
    }
}
